package com.xingfei.blog.interceptor;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.xingfei.blog.controller.ArticleController;
import com.xingfei.blog.service.WebEmailService;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.CookieUtil;
import com.xingfei.blog.utils.UserThreadLocal;
import com.xingfei.blog.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截器,判断用户是否登录
 * Created by yhang on 2017/1/22.
 */
public class GlobalInterceptor implements HandlerInterceptor {

    /**
     * 日志
     */
    public static final Logger logger = LoggerFactory.getLogger(ArticleController.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = CookieUtil.getCookieValue(request,"token");
        String XRequested =request.getHeader("X-Requested-With");
        if(StringUtils.isEmpty(token)){
            //区分通过邮件调用的访问url
            String requestURI = request.getRequestURI();
            String queryString = request.getQueryString();
            if(requestURI.equals("/email/personalConfirm") && queryString.contains("ak=")){
                token = queryString.split("=")[1];
                BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
                WebEmailService emailService = (WebEmailService) factory.getBean("webEmailService");
                boolean flag = emailService.checkEmailCode(token);
                if(flag){
                    request.setAttribute("emailPoint","邮箱绑定成功！");
                    response.sendRedirect("/index");
                    return false;
                }else{
                    response.sendRedirect("/error/jianyi-500");
                    return false;
                }
            }
            //token为null,跳转首页登录
            if("XMLHttpRequest".equals(XRequested)){
                //ajax请求 http://www.jb51.net/article/100787.htm
                logger.info("==================>>>>>>>>>>>>>>>>>>>>>>>ajax请求，用户未登陆，跳转登陆页面<<<<<<<<<<<<<<<<<<<<<<<=================");
                response.getWriter().write("IsAjax");
                return false;
            }else{
                logger.info("==================>>>>>>>>>>>>>>>>>>>>>>>用户未登陆，跳转登陆页面<<<<<<<<<<<<<<<<<<<<<<<=================");
                response.sendRedirect("/login");
                return false;
            }
        }
        //保存用户信息到当前线程中
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            WebUserService  webUserService = (WebUserService) factory.getBean("webUserService");
            UserVO user4Redis = webUserService.getUser4Redis(request);
            if(user4Redis!=null){
                UserThreadLocal.set(user4Redis);
            }else{
            logger.info("==================>>>>>>>>>>>>>>>>>>>>>>>redis token失效，跳转登陆页面<<<<<<<<<<<<<<<<<<<<<<<=================");
            response.sendRedirect("/login");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
